from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
import uuid
from chroma_client import chroma_client
from embedding import embedding_model

router = APIRouter(tags=["knowledge"], prefix="/api")


class KnowledgeItem(BaseModel):
    id: Optional[str] = None
    content: str
    metadata: Optional[Dict[str, Any]] = None


@router.get("/knowledge", response_model=List[KnowledgeItem])
async def get_all_knowledge():
    """获取所有知识项"""
    try:
        return chroma_client.get_all_items()
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取知识库失败: {str(e)}")


@router.get("/knowledge/{item_id}", response_model=KnowledgeItem)
async def get_knowledge_item(item_id: str):
    """获取特定知识项"""
    try:
        item = chroma_client.get_item(item_id)
        if not item:
            raise HTTPException(status_code=404, detail="知识项不存在")
        return item
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取知识项失败: {str(e)}")


@router.post("/knowledge", response_model=KnowledgeItem)
async def add_or_update_knowledge(item: KnowledgeItem):
    """添加或更新知识项"""
    try:
        item_id = item.id or str(uuid.uuid4())
        embedding = embedding_model.encode(item.content)

        chroma_client.add_item(
            item_id=item_id,
            content=item.content,
            metadata=item.metadata,
            # embedding=embedding
        )

        return {
            "id": item_id,
            "content": item.content,
            "metadata": item.metadata
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加/更新知识项失败: {str(e)}")


@router.delete("/knowledge/{item_id}")
async def delete_knowledge_item(item_id: str):
    """删除知识项"""
    try:
        chroma_client.delete_item(item_id)
        return {"status": "success", "message": "知识项已删除"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除知识项失败: {str(e)}")
